package com.bolt.core.view.freemarker;

import com.bolt.common.utils.StrUtil;
import com.bolt.core.view.components.ComponentsBase;
import com.bolt.core.view.components.ValidatorRule;
import com.bolt.core.view.config.ConfigUtils;
import com.bolt.support.freemarker.DirectiveUtil;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Administrator on 2019/4/18.
 */
public abstract class InputModel extends TagModel {


    public String getAttribute(Map<String, TemplateModel> params) {
        return DirectiveUtil.getString(params, "attribute");
    }

    public String getName(Map<String, TemplateModel> params) {
        return DirectiveUtil.getString(params, "name");
    }

    public String getId(Map<String, TemplateModel> params) {
        return DirectiveUtil.getString(params, "id");
    }

    public String getValidate(Map<String, TemplateModel> params) {
        return DirectiveUtil.getString(params, "validate");
    }

    public String getValidateMessage(Map<String, TemplateModel> params) {
        return DirectiveUtil.getString(params, "validateMessage");
    }

    protected ValidatorRule handleValidator(Map<String, TemplateModel> params) {
        ValidatorRule validator = new ValidatorRule();
        String[] vals = StrUtil.split(getValidate(params), "|");
        for (int i = 0; i < vals.length; i++) {
            validator.handleValidatorValue(vals[i]);
        }
        String[] messages = StrUtil.split(getValidateMessage(params), "|");
        ;
        for (int i = 0; i < messages.length; i++) {
            validator.addMessage(messages[i]);
        }
        validator.setId(getId(params));
        return validator;
    }

    public void render(ComponentsBase component , Environment env, Map<String, TemplateModel>  params, TemplateDirectiveBody body) throws IOException, TemplateException{
        populateParams(component,params);
        component.end(getRequest(), getResponse(), env.getOut());
    }

    protected void populateParams(ComponentsBase component, Map<String, TemplateModel>  params) {
        super.populateParams(component,params);
        component.setId(getId(params));
        component.setName(getName(params));
        if (StrUtil.isNotBlank(getValidate(params)) || StrUtil.isNotBlank(getValidateMessage(params))) {
            ValidatorRule v = handleValidator(params);
            if(v != null){
                component.addParameter("validator", v);
            }
        }
        String attribute = getAttribute(params);
        if(StrUtil.isNotBlank(attribute)){
            ConfigUtils.parserConfigText(component,attribute);
        }
    }

}

 